import {LegalHoliday} from "tyme4ts";

export function dateFormat(date: Date | string = new Date(), formatter = "yyyy-MM-dd"): string {
  let tmp: Date;
  if (date instanceof Date) {
    tmp = date;
  } else {
    tmp = new Date(date);
  }

  const paddingZero = (num: number): string => {
    return `${num}`.padStart(2, "0");
  };
  const day = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  const obj: Record<string, string | number | ((dateData: Date) => string | number)> = {
    "Y{4}": (dateData: Date) => dateData.getFullYear(),
    "y+": (dateData: Date) => dateData.getFullYear(),
    "M{2}": (dateData: Date) => paddingZero(dateData.getMonth() + 1),
    "D{2}": (dateData: Date) => paddingZero(dateData.getDate()),
    "d{2}": (dateData: Date) => paddingZero(dateData.getDate()),
    "H{2}": (dateData: Date) => paddingZero(dateData.getHours()),
    "h{2}": (dateData: Date) => paddingZero(dateData.getHours() % 12),
    "m{2}": (dateData: Date) => paddingZero(dateData.getMinutes()),
    "s{2}": (dateData: Date) => paddingZero(dateData.getSeconds()),
    "M": (dateData: Date) => dateData.getMonth() + 1,
    "d": (dateData: Date) => dateData.getDate(),
    "H": (dateData: Date) => dateData.getHours(),
    "h": (dateData: Date) => dateData.getHours() % 12,
    "m": (dateData: Date) => dateData.getMinutes(),
    "s": (dateData: Date) => dateData.getSeconds(),
    "CW": (dateData: Date) => day[dateData.getDay()],
    "W": (dateData: Date) => dateData.getDay()
  };
  const objEntries = Object.entries(obj);
  for (let i = 0; i < objEntries.length; i++) {
    const key = objEntries[i][0];
    const value = objEntries[i][1];
    const regexp = new RegExp(`(${key})([^a-zA-Z])?`);
    const match = regexp.exec(formatter);
    if (match) {
      formatter = formatter.replace(match[1], `${(value as Function)(tmp)}`);
    }
  }
  return formatter;
}

export function getOffsetDate(prevNumber = 1, date: Date = new Date()) {
  let offsetDate = new Date(date)
  offsetDate.setDate(date.getDate() + prevNumber);
  return offsetDate;
}

export function getLastWorkDate() {
  let date = getOffsetDate(-1);
  let holiday = LegalHoliday.fromYmd(date.getFullYear(), date.getMonth() + 1, date.getDate());
  while (holiday !== null || ![1, 2, 3, 4, 5].includes(date.getDay())) {
    date = getOffsetDate(-1, date);
    holiday = LegalHoliday.fromYmd(date.getFullYear(), date.getMonth() + 1, date.getDate());
  }
  return date;
}

export enum NumberUnit {
  Wan,
  Yi
}

export function numberFormat(value: number | string, fixed: number = 2, unit: NumberUnit = NumberUnit.Wan) {
  let tmp = +value;
  switch (unit) {
    case NumberUnit.Wan:
      return +(tmp / 10000).toFixed(fixed) + "万";
    case NumberUnit.Yi:
      return +(tmp / 10000 / 10000).toFixed(fixed) + "亿";
    default:
      return tmp + "万";
  }
}
